import React from 'react';
import { observer, inject } from 'mobx-react';
import classNames from 'classnames';
import { List, Button, DatePicker, Icon, Picker, Tools } from 'weaver-mobile';
import { Browser, BrowserHrm } from 'weaver-mobile-page';
import { dateType } from '../../../components/form/statistics/typeof';
import If from '../../../common/if';
import _ from 'lodash';
import _u from '../../../utils';
import { getWeekList } from '../../../utils/getWeekList';
import './index.less';

const { FormItem } = List;
const { BYDAY, BYALL, BYWEEK } = dateType;
const getLabel = Tools.getLabel; 

@inject('formStatisticsStore')
@observer
export default class SearchAdvanced extends React.Component {
  constructor(props) {
    super(props);

    this.store = props.formStatisticsStore;
    this.state = {
      condition: _.cloneDeep(props.condition)
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.visible!==this.props.visible) {
      this.setState({ condition: _.cloneDeep(nextProps.condition)});
    }
  }

  onChange = obj => {
    const { condition } = this.state;
    const { dateType } = condition;

    if (Object.keys(obj)[0] === 'selectedDate') {
      if (dateType === BYWEEK) {
        const startDate = obj.selectedDate;
        let endDate = new Date(new Date(startDate).setDate(new Date(startDate).getDate() + 6));
      
        endDate = _u.dateFormat('YY-mm-dd', endDate);
        obj.selectedDate = [startDate, endDate];
      }
    }

    Object.assign(condition, obj);
    this.setState({ condition });
  }

  reset = () => {
    this.setState({
      condition: {
        dateType: BYDAY,
        userId: '',
        users: [],
        deptId: '',
        depts: [],
        selectedDate: _u.dateFormat('YY-mm-dd', new Date())
      }
    });
  }

  search = () => {
    const { toggleVisible, onSearch } = this.props;
    const { condition } = this.state;

    onSearch(condition);
    toggleVisible();
  }

  dateType = () => {
    const { dateType } = this.state.condition;

    return (
      <div className='date-type-selected'>
        <span
          className={classNames({'checked': dateType === BYDAY})} 
          onClick={() => {this.onChange({'dateType': BYDAY})}}
        >
          {getLabel(523301, '按天统计')}
        </span>
        <span
          className={classNames({'checked': dateType === BYWEEK})} 
          onClick={() => {this.onChange({'dateType': BYWEEK})}}
        >
          {getLabel(523302, '按周统计')}
        </span>
        <span 
          className={classNames({'checked': dateType === BYALL})}
          onClick={() => {this.onChange({'dateType':  BYALL})}}
        >
          {getLabel(523303, '全部日期')}
        </span>
      </div>
    )
  }

  browseHrm = () => {
    const { browserHrm } = this.store;
    const { users = [] } = this.state.condition;

    return (
      <BrowserHrm
        store={browserHrm}
        hasAdvanceSerach
        isSingle={false}
        type={1}
        onChange={(value, valueSpan, valueArray) => {
          this.onChange({ userId: value, users: valueArray });
        }}
        valueArray={users}
      />
    )
  }

  browseDept = () => {
    const { browser } = this.store;
    const { depts = [] } = this.state.condition;

    return (
      <Browser
        store={browser}
        hasAdvanceSerach
        type={4}
        onChange={(value, valueSpan, valueArray) => {
          this.onChange({ deptId: value, depts: valueArray });
        }}
        tabs={
          [{
            "key": "2",
            "name": getLabel(526988,'组织结构'),
            "dataURL": null,
            "dataParams": null,
            "isSearch": false,
            "showOrder": 0,
            "selected": false
          }, {
            "key": "1",
            "name": getLabel(526987,'按列表'),
            "dataURL": null,
            "dataParams": {
              "list": "1"
            },
            "isSearch": true,
            "showOrder": 0,
            "selected": false
          }]
        }
        valueArray={depts}
      />
    )
  }

  formatDate = date => {
    date = _u.dateFormat('YY-mm-dd', date);
    date = date.split('-');

    date = Number(date[0]) + '/' + Number(date[1]) + '/' + Number(date[2]);

    return date;
  }

  getWeekDate = () => {
    const { appMsg } = this.store;
    const { createDate } = appMsg;
    const startDate = new Date(createDate);
    const weekList = getWeekList(startDate);
    const data = [];

    weekList.forEach(week => {
      data.push({
        label: `${this.formatDate(week.start)}  (${getLabel(523304, '周一')})  ~  ${this.formatDate(week.end)}  (${getLabel(523305, '周日')})`,
        value: _u.dateFormat('YY-mm-dd', week.start)
      });
    });

    return [data];
  }

  getSelectDate = () => {
    const { appMsg } = this.store;
    const { dateType, selectedDate } = this.state.condition;

    let date = _.cloneDeep(selectedDate);

    if (dateType === BYDAY) {
      if (_.isArray(date)) {
        if (new Date(date[1]).getTime() >= new Date().getTime()) {
          date = _u.dateFormat('YY-mm-dd', new Date());
        } else {
          date = date[0] > appMsg.createDate ? date[0] : appMsg.createDate;
        }
      } else {
        date = date || _u.dateFormat('YY-mm-dd', new Date());
      }
    } else if (dateType === BYWEEK) {
      if (_.isArray(date)) {
        date = date;
      } else {
        let startDate = date ? new Date(date) : new Date();
        let endDate = new Date();

        startDate.setDate(startDate.getDate() - startDate.getDay() + 1);

        if (endDate.getDay() === 0) {
          endDate = endDate;
        } else {
          endDate.setDate(endDate.getDate() + 7 - endDate.getDay());
        }
        date = [_u.dateFormat('YY-mm-dd', startDate), _u.dateFormat('YY-mm-dd', endDate)];
      }
    }

    if (!_.isEqual(selectedDate, date)) {
      let localDate = date;

      if (_.isArray(date)) {
        localDate = date[0];
      }

      this.onChange({ 'selectedDate': localDate });
    }

    return date;
  }

  render() {
    const { visible, formStatisticsStore } = this.props;
    const { appMsg } = formStatisticsStore;
    let { dateType } = this.state.condition;

    const selectedDate = this.getSelectDate();

    return (
      <div 
        className={classNames('wea-edc-statistics-advance-search', 
        { 'wea-edc-statistics-advance-search-hide': !visible,  
          'wea-edc-statistics-advance-has-back': window.backBtnAble
        })}
      >
        <List className='list'>
          <FormItem 
            label={getLabel(523306, '统计类型')}
            wrap = "nowrap"
            line
            content={this.dateType()}
          />
          <If condition={dateType === BYDAY}>
            <DatePicker
              mode="date"
              value={selectedDate}
              onChange={date => this.onChange({'selectedDate': date})}
              maxDate={new Date()}
              minDate={appMsg.createDate || '1990-01-01'}
            >
              <div className='date-select'>
                <label>
                  {getLabel(523307, '统计日期')}
                </label>
                  <span>
                  <span>{selectedDate}</span>
                  <Icon type='right'></Icon>
                </span>
              </div>
            </DatePicker>
          </If>
          <If condition={dateType === BYWEEK}>
            <Picker
              data={this.getWeekDate()}
              title={getLabel(523308, "选择统计周")}
              cascade={false}
              value={[selectedDate[0]]}
              onOk={date => this.onChange({ 'selectedDate': date[0] })}
            >
              <div className='date-select'>
                <label>
                  {getLabel(523307, '统计日期')}
                </label>
                <span>
                  <span>
                    <span>{selectedDate[0]}</span>
                    &nbsp;&nbsp;~&nbsp;&nbsp; 
                    <span>{selectedDate[1]}</span>
                  </span>
                  <Icon type='right'></Icon>
                </span>
              </div>
            </Picker>
          </If> 
          <FormItem
            label={getLabel(523309, "填写人")}
            wrap="nowrap"
            line
            content={this.browseHrm()}
          />
          <FormItem
            label={getLabel(523310, "填写人部门")}
            wrap="nowrap"
            line
            content={this.browseDept()}
          />
        </List>
        <footer>
          <Button onClick={this.reset}>{getLabel(523311, '重置')}</Button>
          <Button type='primary' onClick={this.search}>{getLabel(523312, '搜索')}</Button>
      </footer>
      </div>
    )
  }
}